package bookstudytest.nio;

import javax.lang.model.element.NestingKind;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @Auther: Lee
 * @Date: 2018/6/5 12:24
 * @Description:
 */
public class HttpHandler  implements Runnable{
    private int buffersize = 1024;
    private String localCharset = "UTF-8";
    private SelectionKey selectionKey;

    public HttpHandler(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }
    public void handlerAccept() throws IOException {
        SocketChannel accept = ((ServerSocketChannel) selectionKey.channel()).accept();
        accept.configureBlocking(false);
        accept.register(selectionKey.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(buffersize));
    }

    @Override
    public void run() {
        try {
            if (selectionKey.isAcceptable()){
                handlerAccept();
            }
            if (selectionKey.isReadable()){
                handleRead();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void handleRead() throws IOException {
        //获得channel
        SocketChannel accept = (SocketChannel) selectionKey.channel();
        //获取buffer并重置
        ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
        byteBuffer.clear();

        if (accept.read(byteBuffer)==-1){
            accept.close();
        }else {
            byteBuffer.flip();
            String res = Charset.forName(localCharset).newDecoder().decode(byteBuffer).toString();
            String[] requestMessage = res.split("\r\n");
            for (String s : requestMessage) {
                System.out.println(s);
                if (s.isEmpty()){
                    break;
                }
            }
            String[] firstLine = requestMessage[0].split(" ");
            for (String s : firstLine) {
                System.out.println(s);
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("HTTP/1.1 200 OK\r\n");
            stringBuilder.append("Content-Type:text/html;charset:UTF-8\r\n");
            stringBuilder.append("\r\n");
            stringBuilder.append("<html><head>显示报文</head><body>");
            stringBuilder.append("接收到的请求报文：</br>");
            for (String s :requestMessage){
                stringBuilder.append(s+"</br>");
            }
            stringBuilder.append("</body></html>");
            byteBuffer = ByteBuffer.wrap(stringBuilder.toString().getBytes(localCharset));
            accept.write(byteBuffer);
            accept.close();
        }
    }
}
